<?php
class Zendvn_Model_Table_Menu extends Zendvn_Model_Nested{
	protected $_name = 'menu_items';
	
	protected $_id = 'id';
	
	public $_alias = 'node';
	
	public $_searchFields = array();
	
	protected $_listSQL;
	
	public $_arrParam;
	
	public $_options;

	public function itemInSelect($arrParam = null,$options = null){
		$this->_arrParam = $arrParam;
		if($options == null){
			$result = $this->menuAdminSelect();
		}else if($options == 'level'){
			$result = $this->menuAdminLevelSelect();
		}else if($options == 'menu-public'){
			if(!empty($arrParam['menuGroupID']) && $arrParam['menuGroupID'] !='0' ){
				$result = $this->menuPublicLevelSelect();
			}
		}
		
		return $result;
	}
	
	public function getMenuParam($id,$options =  null){
		if($options ==  null){
			$db = $this->getAdapter();
			$select = $db->select()
						 ->from('menu_items',array('params'))					 
						 ->where('id = ?',$id,1);
			$result = $db->fetchOne($select);
		}
		return $result;
	}
	
	public function menuPublicLevelSelect(){
		$db = $this->getAdapter();
		$arrParam = $this->_arrParam;
		if(!isset($arrParam['id'])){
			
			$menuGroupID = $this->_arrParam['menuGroupID'];
			$select = $db->select()
						 ->from('menu_items')					 
						 ->where('menu_group_id = ?','*')
						 ->orWhere('menu_group_id = ?',$menuGroupID)
						 //->where('level = 1')
						 ->order('lft ASC');
			//echo '<br>' . $select;
			
		}else{
			$nodeInfo = $this->getNodeInfo($arrParam['id']);
			$sqlID = $db->select()
						->from('menu_items',array('id'))
						->where('lft >= ?',$nodeInfo['lft'],1)
						->where('rgt <= ?',$nodeInfo['rgt'],1);
			$ids = $db->fetchCol($sqlID);
			
			$menuGroupID = $this->_arrParam['menuGroupID'];
			$select = $db->select()
						 ->from('menu_items')					 
						 ->where('menu_group_id = ?','*')
						 ->orWhere('menu_group_id = ?',$menuGroupID)
						 ->where('id NOT IN (?)' , $ids)
						 ->order('lft ASC');
		}
		$result = $db->fetchAll($select);
		return $result;
	}
	
	public function menuAdminLevelSelect(){
		$db = $this->getAdapter();
		
		$select = $db->select()
					 ->from('menu_items')					 
					 ->where('menu_group_id = ?','*')
					 ->orWhere('menu_group_id = ?','admin')
					 ->where('level = 1')
					 ->order('lft ASC');
		$result = $db->fetchAll($select);
		return $result;
	}
	
	protected function menuAdminSelect(){
		$db = $this->getAdapter();
		
		$select = $db->select()
					 ->from('menu_items')
					 ->where('menu_group_id = ?','*')
					 ->orWhere('menu_group_id = ?','admin')
					 ->order('lft ASC');
	
		if($this->_arrParam['id'] > 0){
			$nodeInfo = $this->getNodeInfo($this->_arrParam['id']);			
			$select2 = $db->select()
						  ->from('menu_items',array('id'))
						  ->where('lft >= ?',$nodeInfo['lft'],1)
						  ->where('rgt <= ?',$nodeInfo['rgt'],1);			
			$select->where('id NOT IN(?)',$db->fetchCol($select2));
		}
		
		$result = $db->fetchAll($select);
		return $result;
	}
	
	public function deleteItem($arrParam = null,$options = null){
		if($options['task'] != 'multi'){
			if($arrParam['id']>0){
				$this->removeNode($arrParam['id']);
			}
		}else{
			if(count($arrParam['cid'])>0){			
				foreach ($arrParam['cid'] as $key => $val){		
					$itemInfo = $this->getNodeInfo($val);
					if(!empty($itemInfo) && $itemInfo['lft']>0){						
						$this->removeNode($val);
					}	
				}
				
			}
		}
	}
	
	public function statusItem($arrParam = null,$options = null){
		if($options == null){
			$status = ($arrParam['s'] == 'active' )? 'inactive':'active';	
			$itemInfo = $this->getNodeInfo($arrParam['id']);
			if($itemInfo['lft'] != 0){
				$data = array('status'=>$status);
				$where = 'lft >= ' . $itemInfo['lft'] . ' AND ' . 'rgt <= ' . $itemInfo['rgt'];
				$this->update($data, $where);
			}
			
		}
		
		if($options['task'] == 'multi'){
		
			$status = $arrParam['s'];				
			if(count($arrParam['cid'])>0){
				foreach ($arrParam['cid'] as $key => $val){
					$itemInfo = $this->getNodeInfo($val);
					if($itemInfo['lft'] != 0){
						$data = array('status'=>$status);
						$where = 'lft >= ' . $itemInfo['lft'] . ' AND ' . 'rgt <= ' . $itemInfo['rgt'];
						$this->update($data, $where);
					}
				}
				
			}
		}
	}
	
	public function sortButton($orderGroupArr,$parents = null,$lft = null){
		
		$str = '';
		if(isset($orderGroupArr[$parents][$lft])){
			$tmp = $orderGroupArr[$parents][$lft];		
			
			if($tmp > 0 ){
				$str .= 'Up ';
			}		
			if($tmp < (count($orderGroupArr[$parents])-1)){
				$str .= 'Down ';
			}
		}
		return $str;
	}
	
	public function getItem($arrParam = null,$options = null){
		if($options == null){
			if(!empty($arrParam['id'])){
				$result = $this->getNodeInfo($arrParam['id']);
				$result['m_module'] 	= $result['module']; 
				$result['m_controller'] = $result['controller']; 
				$result['m_action'] 	= $result['action']; 
				$result['mtype'] 		= $result['type']; 
				$result['m_params'] 	= $result['params']; 
			}
		}
		
		if($options['task'] == 'info'){
			//$where = 'id = ' . (int)$arrParam['id'];
			$db = $this->getAdapter();
			$select = $db->select()
						->from('user_group AS g')
						->joinLeft('users AS u1', 'u1.id = g.created_by', array('u1.email AS created_by'))
						->joinLeft('users AS u2', 'u2.id = g.modified_by', array('u2.email AS modified_by'))
						->where('g.id = ?',$arrParam['id'],1);
			
			$result = $db->fetchRow($select);
		}
		return $result;
	}
	
	public function listItemAll($arrParam = null,$options = null){
		$this->_arrParam 	= $arrParam;
		$this->_options 	= $options;
		
		if($options == null){
			$result = $this->listMenuAdmin();
		}else{
			if($options['task']=='admin-pmenu'){
				$result = $this->listMenuPublic();
				
			}
		}
		
		return $result;
	}	
	
	public function listMenuPublic(){
		$arrParam = $this->_arrParam;
		$options = $this->_options;
		
		$db = $this->getAdapter();		
		$panigator = $arrParam['panigator'];
		$arrFilter = $arrParam['arrFilter'];
		$lang = new Zendvn_Languages();
		$language_code = $lang->getDataLanguage('admin');
		$select = $db->select()
					 ->from('menu_items')	
					 ->where('language_code IN (?)',array('*',$language_code))
					 ->where('menu_group_id = ?','*');
					 
		if(!empty($arrFilter['menu_group_id'])){
			 $select->orWhere('menu_group_id = ?',$arrFilter['menu_group_id']);
		}
		
		if(!empty($arrFilter['keyword']) && !empty($arrFilter['searchField'])){
			$searchField 	= $arrFilter['searchField'];
			$keyword 		= $arrFilter['keyword'];
			if($searchField == 'id' || $searchField == 'parents'){
				$select->where($searchField . ' = ?',trim($arrFilter['keyword']),1);
			}else{
				$keyword = '%'.trim($arrFilter['keyword']) .'%';
			
				$select->where($searchField . " LIKE ?", $keyword);
			}
		}
		
		if(!empty($arrFilter['status']) && $arrFilter['status'] != 'none'){
			$select->where('status = ?',$arrFilter['status']);
		}
		
		if(!empty($arrFilter['col']) && !empty($arrFilter['order'])){
			//$select->where('status = ?',$arrFilter['status']);
			$select->order($arrFilter['col'] . ' ' . $arrFilter['order'])	;
		}
		
		if($arrFilter['level']>0){
			$select->where('level <= ?',$arrFilter['level'],1);
		}
		if($arrFilter['parentNode']>1){
			$nodeInfo = $this->getNodeInfo($arrFilter['parentNode']);			
			$select->where('lft >= ?',$nodeInfo['lft'],1);
			$select->where('rgt <= ?',$nodeInfo['rgt'],1);
		}
		
		$this->_listSQL = $select;
		//echo $select;
		$select->limitPage($panigator['page'], $panigator['rowCount']);
		
//	/	echo '<br>' .  $select;
		
		$result = $db->fetchAll($select);		
		//$result = $this->orderGroup($result);
		return $result;
	}
	
	public function listMenuAdmin(){
		$arrParam = $this->_arrParam;
		$options = $this->_options;
		
		$db = $this->getAdapter();		
		$panigator = $arrParam['panigator'];
		$arrFilter = $arrParam['arrFilter'];
		$select = $db->select()
					 ->from('menu_items')					
					 ->where('menu_group_id = ?','*')
					 ->orWhere('menu_group_id = ?','admin');
					 //->where('level >0')
		
		if(!empty($arrFilter['keyword']) && !empty($arrFilter['searchField'])){
			$searchField 	= $arrFilter['searchField'];
			$keyword 		= $arrFilter['keyword'];
			if($searchField == 'id' || $searchField == 'parents'){
				$select->where($searchField . ' = ?',trim($arrFilter['keyword']),1);
			}else{
				$keyword = '%'.trim($arrFilter['keyword']) .'%';
			
				$select->where($searchField . " LIKE ?", $keyword);
			}
		}
		
		if(!empty($arrFilter['status']) && $arrFilter['status'] != 'none'){
			$select->where('status = ?',$arrFilter['status']);
		}
		
		if(!empty($arrFilter['col']) && !empty($arrFilter['order'])){
			//$select->where('status = ?',$arrFilter['status']);
			$select->order($arrFilter['col'] . ' ' . $arrFilter['order'])	;
		}
		
		if($arrFilter['level']>0){
			$select->where('level <= ?',$arrFilter['level'],1);
		}
		if($arrFilter['parentNode']>1){
			$nodeInfo = $this->getNodeInfo($arrFilter['parentNode']);			
			$select->where('lft >= ?',$nodeInfo['lft'],1);
			$select->where('rgt <= ?',$nodeInfo['rgt'],1);
		}
		
		$this->_listSQL = $select;
		//echo $select;
		$select->limitPage($panigator['page'], $panigator['rowCount']);
		
		//echo '<br>' .  $select;
		
		$result = $db->fetchAll($select);		
		//$result = $this->orderGroup($result);
		return $result;
	}
	
	public function getData($arrParam = null, $options = 'sort-action'){
		
		if($options == 'sort-action'){
			$lftArray  =  array_keys($arrParam['ordering']);	
			$lftArray[] = 0;		
			$sql = $this->select()
				 		->from($this->_name)
				 		->where('lft IN (?)',$lftArray)
				 		->order('lft ASC');
			
			$result = $this->fetchAll($sql)->toArray();
		}
		
		return $result;
	}
	
	public function totalItem($arrParam = null,$options = null){
		$db = $this->getAdapter();
		
		$this->_listSQL->reset(Zend_Db_Select::COLUMNS);
		$this->_listSQL->reset(Zend_Db_Select::LIMIT_COUNT);
		$this->_listSQL->reset(Zend_Db_Select::LIMIT_OFFSET);
		$this->_listSQL->columns('COUNT(id)');		
		$result = $db->fetchOne($this->_listSQL);
		return $result;
		
	}
	
	public function saveItem($arrParam = null, $options = null){			
		
		if($options == null){
			if(!empty($arrParam['id'])){
				//=================== Edit Action ==================
				$data 			= array(
										'name' 			=> $arrParam['name'],
										'alias' 		=> $arrParam['alias'],
										'module' 		=> $arrParam['m_module'],
										'controller' 	=> $arrParam['m_controller'],
										'action' 		=> $arrParam['m_action'],
										'params' 		=> $arrParam['m_params'],
										'router' 		=> $arrParam['router'],
										'type' 			=> $arrParam['mtype'],
										'url' 			=> $arrParam['url'],
										'status' 		=> $arrParam['status'],
										'menu_group_id' => $arrParam['menu_group_id'],
										'language_code' => '*'
									    );		
				$id 			= $arrParam['id'];
				$newParentId 	= $arrParam['parents'];
				$this->updateNode($data, $id, $newParentId);
			}else{
				//==================== Add Action ==================
				$data 			= array(
										'name' 			=> $arrParam['name'],
										'alias' 		=> $arrParam['alias'],
										'module' 		=> $arrParam['m_module'],
										'controller' 	=> $arrParam['m_controller'],
										'action' 		=> $arrParam['m_action'],
										'params' 		=> $arrParam['m_params'],
										'router' 		=> $arrParam['router'],
										'type' 			=> $arrParam['mtype'],
										'url' 			=> $arrParam['url'],
										'status' 		=> $arrParam['status'],
										'menu_group_id' => $arrParam['menu_group_id'],
										'language_code' => '*'
									    );
				$this->insertNode($data, $arrParam['parents'], $options);
			}
		}elseif ($options == 'public'){
			
			$cparam = $arrParam['cparam'];
			$m_params = $arrParam['cparam'];
			unset($m_params['module']);
			unset($m_params['controller']);
			unset($m_params['action']);
			
			$newParams = '';
			if($arrParam['mtype'] == 'module'){
				$newParams = Zend_Json::encode($m_params);
			}
			
			$lang = new Zendvn_Languages();
			$language_code = $lang->getDataLanguage('admin');
			if(!empty($arrParam['id'])){
				//=================== Edit Action ==================
				
				$data 			= array(
										'name' 			=> $arrParam['name'],
										'alias' 		=> $arrParam['alias'],
										'module' 		=> $cparam['module'],
										'controller' 	=> $cparam['controller'],
										'action' 		=> $cparam['action'],
										'params' 		=> $newParams,
										'router' 		=> $arrParam['router'],
										'type' 			=> $arrParam['mtype'],
										'url' 			=> $arrParam['url'],
										'function_id' 	=> $arrParam['function_id'],
										'status' 		=> $arrParam['status'],
										'menu_group_id' => $arrParam['menu_group_id'],
										'language_code' => $language_code
									    );
					
				$id 			= $arrParam['id'];
				$newParentId 	= $arrParam['parents'];
				
				$this->updateNode($data, $id, $newParentId);
			}else{
				//==================== Add Action ==================
				$data 			= array(
										'name' 			=> $arrParam['name'],
										'alias' 		=> $arrParam['alias'],
										'module' 		=> $cparam['module'],
										'controller' 	=> $cparam['controller'],
										'action' 		=> $cparam['action'],
										'params' 		=> $newParams,
										'router' 		=> $arrParam['router'],
										'type' 			=> $arrParam['mtype'],
										'url' 			=> $arrParam['url'],
										'function_id' 	=> $arrParam['function_id'],
										'status' 		=> $arrParam['status'],
										'menu_group_id' => $arrParam['menu_group_id'],
										'language_code' => $language_code
									    );
				$this->insertNode($data, $arrParam['parents']);
			}
			
		}
	}
}